﻿## This script using the Windows Azure AD Module, follow the link below to install it
## http://msdn.microsoft.com/en-us/library/azure/jj151815.aspx

Import-Module MSOnline
Import-Module MSOnlineExtended

# check to see if $cred exists, supports rerunning of the script without reprompting the user
# if you want to use new credentials then execute Remove-Variable cred
if (!(Test-Path variable:\cred)) {
    #prompt for credentials to connect to service
    $cred = Get-Credential
    Connect-MsolService -Credential $cred
}

$clientId = ([System.Guid]::NewGuid()).Guid
$servicePrincipalName = "AzureAD-Client-$clientId"
$clientSecret = "SET YOUR PASSWORD HERE"  #you will want to change this password for your environment

$servicePrincipal = New-MsolServicePrincipal -ServicePrincipalNames $servicePrincipalName -DisplayName $servicePrincipalName -AppPrincipalId $clientId -Type Password -Value $clientSecret
Write-Host "Created ServicePrincpal:"
Write-Host " servicePrincipalName: $servicePrincipalName"
Write-Host " clientId: $clientId"
Write-Host " clientSecret: $clientSecret"

#need to assign permissions
Add-MsolRoleMember -RoleName "Company Administrator" -RoleMemberType ServicePrincipal -RoleMemberObjectId $servicePrincipal.ObjectId

#check to see that the servicePrincipal is in the role, except this doesn't seem to list ServicePrincipals
#Get-MsolRoleMember -RoleObjectId (Get-MsolRole -RoleName "Company Administrator").ObjectId

#If needed you can change the password
# if need to lookup names
#   Get-MsolServicePrincipal | Where-Object {$_.DisplayName -like 'AzureAD-Client-*'} | Select-Object ObjectId, DisplayName
# and then replace <objectId-guid> with the guid for the principal  
#   New-MsolServicePrincipalCredential -ObjectId <objectId-guid> -Type Password -Value "NEW PASSWORD"

